package com.ycrlkj.android.modulescore.main.activity.amap;

import android.app.Activity;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.amap.api.maps.AMap;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.navi.NaviSetting;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkRouteResult;
import com.blankj.utilcode.util.ToastUtils;
import com.ycrlkj.android.modulesbase.libbase.utils.Logger;
import com.ycrlkj.android.modulescore.main.R;
import com.ycrlkj.android.modulescore.main.databinding.FragmentMapRouteBinding;

import dagger.hilt.android.AndroidEntryPoint;

@AndroidEntryPoint
public class MapRouteFragment extends Fragment {

    private FragmentMapRouteBinding binding;

    private Activity activity;

    private MapView mapView;
    private AMap aMap;

    private Double startLat;
    private Double startLng;
    private Double endLat;
    private Double endLng;

    public MapRouteFragment() {
    }

    public static MapRouteFragment newInstance(Double startLat, Double startLng, Double endLat, Double endLng) {
        MapRouteFragment fragment = new MapRouteFragment();
        Bundle bundle = new Bundle();
        bundle.putDouble("startLat", startLat);
        bundle.putDouble("startLng", startLng);
        bundle.putDouble("endLat", endLat);
        bundle.putDouble("endLng", endLng);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_map_route, container, false);
        activity = getActivity();

        if(getArguments() != null){
            startLat = getArguments().getDouble("startLat");
            startLng = getArguments().getDouble("startLng");
            endLat = getArguments().getDouble("endLat");
            endLng = getArguments().getDouble("endLng");
        }

        initMap(savedInstanceState);

        return binding.getRoot();
    }


    public void initMap(Bundle savedInstanceState) {

        NaviSetting.updatePrivacyShow(activity, true, true);
        NaviSetting.updatePrivacyAgree(activity, true);

        mapView = binding.map;
        mapView.onCreate(savedInstanceState);

        aMap = mapView.getMap();

        //定义一个UiSettings对象
        UiSettings uiSettings = aMap.getUiSettings();//实例化UiSettings类对象

        //uiSettings.setAllGesturesEnabled(false);//所有手势
        uiSettings.setZoomGesturesEnabled(true);//缩放手势
        uiSettings.setScrollGesturesEnabled(true);//滑动手势
        uiSettings.setRotateGesturesEnabled(false);//旋转手势
        uiSettings.setTiltGesturesEnabled(false);//倾斜手势

        routeSearch();
    }

    public void routeSearch() {
        RouteSearch.OnRouteSearchListener onRouteSearchListener = new RouteSearch.OnRouteSearchListener() {
            //驾车路线回调
            @Override
            public void onDriveRouteSearched(DriveRouteResult driveRouteResult, int errorCode) {
                aMap.clear();// 清理地图上的所有覆盖物
                if (errorCode == 1000) {
                    if (driveRouteResult != null && driveRouteResult.getPaths() != null) {
                        if (driveRouteResult.getPaths().size() > 0) {
                            final DrivePath drivePath = driveRouteResult.getPaths().get(0);
                            DrivingRouteOverlay drivingRouteOverlay = new DrivingRouteOverlay(activity, aMap, drivePath, driveRouteResult.getStartPos(), driveRouteResult.getTargetPos(), null);
                            drivingRouteOverlay.setNodeIconVisibility(false);//设置节点marker是否显示
                            drivingRouteOverlay.setIsColorfulline(true);//是否用颜色展示交通拥堵情况，默认true
                            drivingRouteOverlay.removeFromMap();
                            drivingRouteOverlay.addToMap();
                            drivingRouteOverlay.zoomToSpan();

                            int dis = (int) drivePath.getDistance();
                            int dur = (int) drivePath.getDuration();
                            Logger.e("dis = " + dis);
                            Logger.e("dur = " + dur);

                        } else if (driveRouteResult.getPaths() == null) {
                            ToastUtils.showLong("未找到路线");
                        }

                    } else {
                        ToastUtils.showLong("获取到路线失败");
                    }
                } else {
                    ToastUtils.showLong("请求获取路线失败");
                }

            }

            @Override
            public void onBusRouteSearched(BusRouteResult busRouteResult, int i) { }

            @Override
            public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) { }

            @Override
            public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) { }
        };


        try {
            RouteSearch routeSearch = new RouteSearch(activity);
            routeSearch.setRouteSearchListener(onRouteSearchListener);

            LatLonPoint mStartPoint = new LatLonPoint(startLat, startLng);
            LatLonPoint mEndPoint = new LatLonPoint(endLat, endLng);
            RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(mStartPoint, mEndPoint);

            // 起点终点，驾车模式:0=>速度优先，途径点（最多支持6个），避让区域（最多支持32个），避让道路
            RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(fromAndTo, 0, null, null, "");
            routeSearch.calculateDriveRouteAsyn(query);// 异步路线规划驾驶模式查询
        } catch (AMapException e) {
            e.printStackTrace();
            ToastUtils.showLong("生成驾车路线失败");
        }

    }

    /**
     * 必须重写以下方法
     */
    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }
}